#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>

void sigchld_t(int signum){
	printf("%s\n",strsignal(signum));
	wait(NULL);
}
void sigalrm_t(int);
typedef void (*sighandler_t)(int);

char buf[128]={0};
int count=0;
int main(){
	sighandler_t handler=signal(SIGCHLD,sigchld_t);
	if(handler==SIG_ERR){
		psignal(SIGCHLD,"signal");
		exit(1);
	}
	sighandler_t handler1=signal(SIGALRM,sigalrm_t);
	if(handler1==SIG_ERR){
		psignal(SIGALRM,"signal");
		exit(1);
	}
	pid_t pid=fork();
	if(pid==-1){
		sleep(1);
		perror("fork");
		exit(1);
	}
	if(pid==0){
		printf("fork\n");
		alarm(2);	
		fgets(buf,sizeof(buf),stdin);
		buf[strlen(buf)-1]='\0';
		while(1);
	}else{
		pause();
		printf("Main OK\n");
	}
	signal(SIGCHLD,handler);
	signal(SIGALRM,handler1);
	return 0;
}
void sigalrm_t(int signum){
	if(strlen(buf)!=0){
		printf("buf=%s\n",buf);
		exit(0);
	}else{
		count++;
		if(count<=3){
			printf("第%d次提醒:\n",count);
			alarm(2);
		}else{
			exit(1);	
		}
	}
}
